#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""This is program can be used to download torrent from jandown.com or mimima.com
by a argument such as 'http://www.jandown.com/link.php?ref=PDR4ZIzDaI' OR
'http://www6.mimima.com/link.php?ref=wi0ArNNCtd', The general usage of this file is:
Windows:
if a proxy is used: ./jd.py url -p True ; default no proxy is used.
"""


from Functions import *
import requests
import random
import sys
import os
from optparse import OptionParser


# Check the number of arguments
if len(sys.argv) == 1:
    raise Exception("The number of arguments should not be empty...")

str_download = sys.argv[1]
param_dict = parse_params(str_download)
str_post_url = 'http://%s/fetch.php' % param_dict['host']
str_host = param_dict['host']
boundary = '-----------------------------' + str(int(random.random()*1e10))
save_path = param_dict['ref'] + '.torrent'
current_path = os.getcwd()

# fetch request
req = requests.get(str_download)


# post body
parts = list()
parts.append('--'+boundary)
parts.append('Content-Disposition: form-data; name="code"\r\n')
parts.append(param_dict['ref'])
parts.append('--'+boundary+'--')
data_body = '\r\n'.join(parts)


# post headers
post_headers = dict()
post_headers['Referer'] = str_download
post_headers['Content-Type'] = 'multipart/form-data; boundary=%s' % boundary
post_headers['Content-Length'] = len(data_body) + 2
post_headers['Host'] = str_host
post_headers['Accept-Encoding'] = 'gzip, deflate'


# check if it is needed to use proxy
parser = OptionParser(usage="usage:%prog [optinos] filepath")
parser.add_option("-p", "--proxy",
                  action="store_true",
                  dest="proxy",
                  default=False,
                  help="flags about use proxy default True")
(options, args) = parser.parse_args()

if not options.proxy:
    proxies = dict()
else:
    proxies = {
        'http': 'http://127.0.0.1:1080',
        'https': 'http://127.0.0.1:1080',
    }


# send post and fetch request
full_path = os.path.join(current_path, save_path)
respond = requests.post(str_post_url, data=data_body, headers=post_headers, cookies=req.cookies, proxies=proxies)
with open(full_path, 'wb') as f:
    for chunk in respond.iter_content(1024):
        f.write(chunk)
print 'finished download file %s' % full_path












